import json
import time
import random
from alipay import AliPay
from flask import Blueprint,jsonify,g
from flask_restful import Api,Resource,marshal, reqparse

from common.utlis.name_list import path_fields
from common.utlis.name_list import course_fields
from models import db
from models.paths import JieDuan

path_bp = Blueprint('path',__name__, url_prefix='/path')
api = Api(path_bp)

class PathesRespurce(Resource):
    def get(self):
        """获取所有的路径"""
        # 获取所有学习的阶段及阶段下的所有课程

        jieduan = JieDuan.query.all()
        data_ = []
        print(jieduan)
        for i in jieduan:
            # 动态给对象添加属性
            # 给阶段添加一个字段: section_sum 来存放该阶段下的课程数量

            # i.section_sum = len(i.course)
            data_.append({
                'section_sum': len(i.course),
                'id': i.id,
                'title': i.title,
                'img': i.img,
                'ser_num':i.ser_num,
                'desc': i.desc
            })
        return jsonify(message="ok", code=200, data=data_)


class PathInfoResource(Resource):
    def get(self):
        """获取单个路径信息"""
        parser = reqparse.RequestParser()
        parser.add_argument('pid')
        args = parser.parse_args()
        jieduan = JieDuan.query.filter_by(id=args.get('pid')).first()
        path_info = json.loads(json.dumps(marshal(jieduan, path_fields)))

        # 获取阶段下所有的课程
        course_data = json.loads(json.dumps(marshal(jieduan.course, course_fields)))

        # 组装stage_info
        stage_info = []
        stage_info.append({
            'id': jieduan.id,
            'stage':jieduan.ser_num,
            'stage_name': jieduan.title,
            'coursedata': course_data
        })
        return jsonify(message="ok", code=200, data={'path_info':path_info,'stage_info':stage_info})



api.add_resource(PathesRespurce, '/get_path')
api.add_resource(PathInfoResource,'/get_path_info')